#!/bin/bash
#write by jerry
real_dir=$(dirname `/usr/sbin/lsof -p $$ | gawk '$4 =="255r"{print $NF}'`)
swoole_script="${real_dir}/SwooleServer.php"
function start_swoole()
{
    printf "Starting SwooleServer Port ${port} ...\n"
    nohup php $swoole_script > /var/log/swoole_${port}.out 2>&1 &
	sleep 2
    netstat -ltnp |grep $port
}

function stop_swoole()
{
    printf "Stoping SwooleServer Port ${port} ...\n"
	lsof -t -i:$port && {
    kill $(lsof -t -i:$port)
	}
}

function restart_swoole()
{
    printf "Restarting SwooleServer Port ${port} ...\n"
    stop_swoole
    sleep 3
    start_swoole
}

function readini() {
    INIFILE=$1;	SECTION=$2;	ITEM=$3
    _readIni=`awk -F '=' '/\['$SECTION'\]/{a=1}a==1&&$1~/'$ITEM'/{print $2;exit}' $INIFILE`
    echo ${_readIni}|sed s/[[:space:]]//g
}
port=$(readini "${real_dir}/app.ini" common swoole.port)
if [ -z $port ];then
    echo '获取port失败!'
    exit
fi

if [ "$1" = "start" ]; then
    start_swoole
elif [ "$1" = "stop" ]; then
    stop_swoole
elif [ "$1" = "restart" ]; then
    restart_swoole
else
    printf "Usage: /bin/bash swoole_manage.sh {start;stop;restart}\n"
fi